<template>
  <div class="text-xl">【文章发布热力图】</div>
  <div ref="target" class="w-full h-72 pt-12 pl-3"></div>
</template>

<script setup>
import * as echarts from 'echarts';
import { watch, ref, onMounted } from 'vue'
import { format, subMonths } from 'date-fns'
import { getPublishArticleStatisticsInfo } from '@/api/admin/dashboard'



// 按日统计文章发布数据
const articlePublishInfo = ref({})

const getPublishArticleInfo = async () => {
    const res = await getPublishArticleStatisticsInfo()
    if (res.success) {
        articlePublishInfo.value = res.data
    }
}
getPublishArticleInfo()


// 日历热点数据
const myData = []
const target = ref(null)
let myChart = null

onMounted(() => {
  myChart = echarts.init(target.value)
  init()
})

// 当前日期
const currentDate = new Date();
// 半年前
const sixMonthsAgo = subMonths(currentDate, 6)

// 格式化后的开始、结束日期
const startDate = format(sixMonthsAgo, 'yyyy-MM-dd')
const endDate = format(currentDate, 'yyyy-MM-dd')



// 初始化日历
function init() {
    // 准备数据
    let map = articlePublishInfo.value
    for (let key in map) {
        myData.push([key, map[key]])
    }
    let option = {
        visualMap: {
            show: false,
            min: 0,
            max: 10
        },
        title: {
            left: 'center',
            text: '2023-2024',
            top: '2%',
            textStyle: {
                color: '#fff',
            }
        },
        calendar: { // 日历显示的范围：开始日期 - 结束日期
            top: 'center',
            left: 30,    
            right: 30,
            range: [startDate, endDate],
            dayLabel: {
                color: '#fff'
            },
            monthLabel: {
                color: '#fff'
            }
        },
        series: {
            type: 'heatmap',
            coordinateSystem: 'calendar',
            data: myData
        },
        gradientColor: [ // 自定义热点颜色，参考了 GitHub 代码提交的颜色
            '#fff',
            '#40c463',
            '#30a14e',
            '#216e39',
        ]
    };
    myChart.setOption(option);
}


// 监听属性, 监听 articlePublishInfo.value 的变化，一旦 props.value 发生变化，就调用 init 初始化日历热点图
watch(() => articlePublishInfo.value, () => init(), {deep: true})

</script>